<template>
  <div style="padding: 10px; border: 1px solid #ccc">
    <el-row>
      <el-col :span="6" class="left">
        <div class="flex mb10 pb10 bdf6">
          <el-button
            style="margin-left: 10px"
            @click="searchCarinfoShow = !searchCarinfoShow"
            type="primary"
            size="mini"
            class="mr10"
          >
            更多<i class="el-icon-search" />
          </el-button>
        </div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="城市搜索" name="first">
            <el-input
              style="width: 75%"
              v-model="input"
              @keyup.enter.native="cityKeySearch"
              placeholder="输入环保编号、名称查询"
              size="mini"
            ></el-input>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="input ? cityKeySearch() : getCityTree()"
              >搜索</el-button
            >

            <!-- 城市树容器 -->
            <div class="treedata">
              <el-tree
                :data="cityTree"
                show-checkbox
                node-key="id"
                :props="treeProps"
                ref="refcity"
                accordion
                @check="cityCheck"
              >
              </el-tree>
            </div>
          </el-tab-pane>

          <el-tab-pane label="类型搜索" name="second">
            <div class="treedata">
              <el-tree
                :data="typeTree"
                show-checkbox
                node-key="id"
                :props="treeProps"
                ref="reftype"
                accordion
                @check="typeCheck"
              >
              </el-tree>
            </div>
          </el-tab-pane>
        </el-tabs>
        <!-- 点搜索出来的弹窗 -->
        <div
          v-show="searchCarinfoShow"
          class="searchCarinfoShow"
          @click="searchCarinfoShow = true"
        >
          <el-form
            :model="searchForm"
            ref="searchForm"
            label-width="100px"
            class="demo-ruleForm"
            size="mini"
          >
            <el-form-item label="卡规则" prop="cardStatus">
              <el-select
                placeholder="请选择"
                size="mini"
                v-model="searchForm.cardStatus"
                style="width: 180px"
              >
                <el-option
                  v-for="item in dict.type.location_card_rule"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排放阶段" prop="emissionStage">
              <el-select
                placeholder="请选择"
                size="mini"
                v-model="searchForm.emissionStage"
                style="width: 180px"
              >
                <el-option
                  v-for="item in dict.type.location_emission_stage"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="尾号限行" prop="endNumber">
              <el-select
                placeholder="请选择"
                size="mini"
                multiple
                v-model="searchForm.endNumber"
                style="width: 180px"
              >
                <el-option
                  v-for="item in dict.type.location_plate_limit"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="flex">
              <el-button type="primary" @click="moreSearch('searchForm')"
                >搜索</el-button
              >
              <el-button @click="resetBtn('searchForm')">重置</el-button>
            </el-form-item>
          </el-form>
          <div style="height: 70%">
            <el-table
              :data="moreData"
              size="mini"
              height="90%"
              @selection-change="moreSearchData"
            >
              <el-table-column type="selection" width="50"></el-table-column>
              <el-table-column
                property="code"
                label="环保编号"
              ></el-table-column>
            </el-table>
            <el-pagination
              style="margin-top: 10px"
              @size-change="handleSizeChangeLeft"
              @current-change="handleCurrentChangeLeft"
              :pager-count="5"
              :current-page="1"
              :page-sizes="[50, 500, 1000, 2000]"
              layout="sizes, prev, pager, next"
              :small="true"
              :total="totalLeft"
            >
            </el-pagination>
          </div>
        </div>
      </el-col>

      <el-col :span="2">
        <div class="opSetting">
          <div @click="handelSelect">
            <el-button
              icon="el-icon-d-arrow-right"
              :disabled="nowSelectData.length ? false : true"
              :size="buttonSize"
              type="primary"
            >
              添加
            </el-button>
          </div>
          <div class="spacing" @click="handleRemoveSelect">
            <el-button
              icon="el-icon-d-arrow-left"
              :disabled="nowSelectRightData.length ? false : true"
              :size="buttonSize"
              type="primary"
            >
              移除
            </el-button>
          </div>
        </div>
      </el-col>

      <el-col :span="16">
        <div style="padding: 10px 0">
          <el-input
            v-model="inputRightCode"
            placeholder="输入环保编号查询"
            size="mini"
            style="width: 50%; margin-right: 5px"
          ></el-input>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="getBindData"
            >搜索</el-button
          >
          <el-button type="primary" size="small" @click="copeTrData()"
            >依例全设</el-button
          >
          <el-button type="primary" size="small" @click="submitForm"
            >保存</el-button
          >
          <el-button type="danger" size="small" plain @click="selectArr = []"
            >清空</el-button
          >
          <el-button
            type="primary"
            size="small"
            plain
            @click="backendExportToExcel"
          >
            导出
          </el-button>
        </div>

        <el-table
          :data="loactiondata"
          height="height: calc(90vh - 164px) !important;"
          border
          ref="selection"
          @selection-change="checkRightAll"
          :header-cell-style="{
            background: '#f2f2f2',
            color: '#333',
            fontSize: '12px',
          }"
          size="mini"
          style="
            width: 100%;
            height: calc(90vh - 164px) !important;
            margin-bottom: 10px;
          "
        >
          <el-table-column type="selection" width="40"> </el-table-column>
          <el-table-column
            prop="date"
            label="序号"
            width="50"
            fixed="left"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="carNo"
            label="监控对象"
            width="120"
            fixed="left"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="sendType"
            label="下发类型"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <el-select
                row
                v-model="scope.row.sendType"
                placeholder="请选择"
                size="mini"
              >
                <el-option
                  v-for="item in xfData"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="alarmSource"
            label="报警来源"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.alarmSource"
                placeholder="请选择"
                size="mini"
              >
                <el-option
                  v-for="item in jkData"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="StartTime"
            label="开始时间"
            width="160"
            align="center"
          >
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.startTime"
                type="date"
                size="mini"
                style="width: 130px"
                placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column
            prop="EndTime"
            label="结束时间"
            width="160"
            align="center"
          >
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.endTime"
                type="date"
                size="mini"
                style="width: 130px"
                placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </template>
          </el-table-column>

          <el-table-column
            prop="alarmIn"
            label="驶入报警给平台"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.alarmIn"
                class="demo"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="alarmOut"
            label="驶出报警给平台"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.alarmOut"
                class="demo"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="alarmInDriver"
            label="驶入报警给驾驶员"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.alarmInDriver"
                class="demo"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="alarmOutDriver"
            label="驶出报警给驾驶员"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.alarmOutDriver"
                class="demo"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="speed"
            label="最高速度(km/h)"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <input
                type="text"
                v-model="scope.row.speed"
                class="cell-input"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="overSpeedTime"
            label="超速持续时间(s)"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <input
                type="text"
                v-model="scope.row.overSpeedTime"
                class="cell-input"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="travelLongTime"
            label="行驶时间过长阈值(s)"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <input
                type="text"
                v-model="scope.row.travelLongTime"
                class="cell-input"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="travelSmallTime"
            label="行驶时间不足阈值(s)"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <input
                type="text"
                v-model="scope.row.travelSmallTime"
                class="cell-input"
              />
            </template>
          </el-table-column>
          <el-table-column prop="openDoor" label="允许开门">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.openDoor"
                class="demo"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="communicationFlag"
            label="进区域开启通信模块"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.communicationFlag"
                class="demo"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="gnssFlag"
            label="进区域不采集GNSS详细定位数据"
            width="250"
            align="center"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.gnssFlag"
                class="demo"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="1"
          :page-sizes="[50, 200, 300, 400]"
          :page-size="pagesize"
          :small="true"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// import ExportJsonExcel from "js-export-excel";
// import axios from "axios";
import api from "@/api/location/fence";

export default {
  dicts: [
    "location_card_rule",
    "location_emission_stage",
    "location_plate_limit",
  ],

  props: {
    toEdit: 0,
    required: true,
  },
  data() {
    return {
      setting: {
        check: {
          enable: true,
          nocheckInherit: false,
          chkboxType: { Y: "ps", N: "ps" },
        },
        data: {
          simpleData: {
            enable: true,
          },
        },
        callback: {
          beforeClick: this.beforeClick,
          onClick: this.zTreeOnClick, //监控点击
          onCheck: this.zTreeOnCheck, //监控勾选
          onExpand: this.zTreeOnExpand, //监控展开
          onAsyncSuccess: this.zTreeOnAsyncSuccess,
        },
        view: {
          fontCss: this.setFontCss,
        },
      },
      zNodes: [],
      activeName: "first",
      inputRightCode: null,
      currentPage: 1,
      currentPageLeft: 1,
      pagesize: 50,
      pagesizeLeft: 50,
      total: 0,
      totalLeft: 0,
      selectArr: [], // 右边列表
      searchCarinfoShow: false,
      moreData: [],
      // ruleForm: {
      //   SendFenceType: "0",
      //   AlarmSource: "",
      //   StartTime: "",
      //   EndTime: "",
      //   AlarmStartTime: "",
      //   AlarmEndTime: "",
      //   AlarmIn: "",
      //   AlarmOut: "",
      //   AlarmInDriver: "",
      //   AlarmOutDriver: "",
      //   Speed: "",
      //   OverSpeedLastTime: "",
      //   TravelLongTime: "",
      //   TravelSmallTime: "",
      //   OpenDoor: "",
      //   CommunicationFlag: "",
      //   GnssFlag: "",
      // },
      buttonSize: "small",
      treedata: [],
      options: [],
      defaultProps: {
        children: "children",
        label: "name",
        isLeaf: "leaf",
      },
      searchForm: {
        cardStatus: "", //卡类别
        emissionStage: "", //排放阶段
        endNumber: "", //尾号
      },
      value: "",
      nowSelectData: [], // 左边选中列表数据
      nowSelectRightData: [], // 右边选中列表数据
      xfData: [
        {
          value: 0,
          label: "更新",
        },
        {
          value: 1,
          label: "追加",
        },
        {
          value: 2,
          label: "修改",
        },
      ],
      jkData: [
        {
          value: 1,
          label: "终端报警",
        },
        {
          value: 2,
          label: "平台报警",
        },
      ],
      card: [
        {
          value: "0",
          label: "全部",
        },
        {
          value: "1",
          label: "绿卡",
        },
        {
          value: "2",
          label: "黄卡",
        },
        {
          value: "3",
          label: "红卡",
        },
        {
          value: "4",
          label: "蓝卡",
        },
      ],
      emissionStage: [
        {
          value: "0",
          label: "全部",
        },
        {
          value: "1-",
          label: "I类",
        },
        {
          value: "2-",
          label: "II类",
        },
        {
          value: "3-",
          label: "III类",
        },
        {
          value: "X-",
          label: "X类",
        },
      ],
      endNumber: [
        { value: "1", label: "1" },
        { value: "2", label: "2" },
        { value: "3", label: "3" },
        { value: "4", label: "4" },
        { value: "5", label: "5" },
        { value: "6", label: "6" },
        { value: "7", label: "7" },
        { value: "8", label: "8" },
        { value: "9", label: "9" },
        { value: "0", label: "0" },
      ],
      fenceId: 0,
      input: "",
      select: [],
      loactiondata: [],

      cityTree: [], //城市树
      typeTree: [], //类型树
      treeProps: { children: "children", label: "label" },
    };
  },
  watch: {
    // currentPage(newData){
    // 	// console.log(newData)
    // 	this.getBindData()
    // }
    selectArr() {
      this.getrecord(this.currentPage);
    },
    toEdit(val) {
      console.log("检测", val);
    },
  },

  mounted() {
    //编辑赋值
    console.log(this.toEdit);
    console.log(Number(this.toEdit) > 0);
    if (Number(this.toEdit) > 0) {
      this.fenceId = Number(this.toEdit);
      this.getBindData();
    }
    this.getCityTree();
    this.getTypeTree();
  },
  created() {
    // let data = { searchType: 0 };
  },
  methods: {
    // tab切换
    handleClick(tab, event) {
      console.log(tab, event);
      if (tab.name == "first") {
        if (this.cityTree.length == 0) {
          this.getCityTree();
        }
      } else if (tab.name == "second") {
        if (this.typeTree.length == 0) {
          this.getTypeTree();
        }
      }
    },
    cityKeySearch() {
      this.$set(this, "cityTree", [
        { id: 0, label: "加载中...", disabled: true },
      ]);
      let params = {
        searchValue: this.input,
      };
      api.groupCarTree(params).then((res) => {
        // console.log("==========>", res);
        if (res.code == 200) {
          this.$set(this, "cityTree", res.data);
        }
      });
    },
    getCityTree() {
      this.$set(this, "cityTree", [
        { id: 0, label: "加载中...", disabled: true },
      ]);
      api.deptTree().then((res) => {
        // console.log("==========>", res);
        if (res.code == 200) {
          let result = [res.data];
          console.log(result);
          result.forEach((leveOne) => {
            leveOne.disabled = true;
            leveOne.children.forEach((leveTwo) => {
              leveTwo.disabled = true;
            });
          });
          this.$set(this, "cityTree", result);
        }
      });
    },
    cityCheck(node, data) {
      console.log(node, data);
      this.nowSelectData = [];
      data.checkedNodes.forEach((item, i) => {
        if (item.deviceNumber) {
          this.nowSelectData.push(item);
        }
      });
      console.log("======>城市当前选择", this.nowSelectData);
    },

    getTypeTree() {
      this.$set(this, "typeTree", [
        { id: 0, label: "加载中...", disabled: true },
      ]);
      api.carTypeTree().then((res) => {
        // console.log("==========>", res);
        if (res.code == 200) {
          let result = res.data;

          this.$set(this, "typeTree", res.data);
        }
      });
    },
    typeCheck(node, data) {
      console.log(node, data);
      this.nowSelectData = [];
      data.checkedNodes.forEach((item, i) => {
        if (item.leaf == 1) {
          this.nowSelectData.push(item);
        }
      });
      console.log("======>当前选择", this.nowSelectData);
    },
    // 清空绑定车辆数据
    cleanCarData() {
      console.log(1231);
      api.addFenceBingding([{ fenceId: this.fenceId }]).then((res) => {
        if (res.code == 200) {
          this.$message.success("保存成功");
        }
      });
    },
    // ===========s
    //加载原有绑定数据
    getBindData() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.5)",
      });

      let params = {
        carNo: this.inputRightCode,
        fenceId: this.fenceId,
      };

      api
        .fenceCarList(params)
        .then((res) => {
          //   this.selectArr = res.data.data;
          console.log("=====表格数据", res);
          let result = res.data;

          this.total = result.length;
          this.selectArr = result;
          loading.close();
        })
        .catch((err) => {
          loading.close();
        });
    },
    //保存
    submitForm() {
      this.$confirm("是否确认保存选中监控车辆数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (this.selectArr.length == 0) {
            this.cleanCarData();
            return;
          }
          let params = this.selectArr;
          params.forEach((item, i) => {
            item.fenceId = this.fenceId;
          });
          console.log(params, "=====传输");

          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.5)",
          });
          api
            .addFenceBingding(params)
            .then((res) => {
              if (res.code == 200) {
                this.$message.success("保存成功");
              }
              loading.close();
            })
            .catch((err) => {
              loading.close();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // ===========e
    //搜索重置
    resetBtn(formName) {
      this.$refs[formName].resetFields();
      this.$store.commit("changeAreaSearchCar", []);
    },
    //更多筛选
    moreSearchData(val) {
      let exampleArr = JSON.parse(JSON.stringify(val));
      if (exampleArr.length > 0) {
        var code = [];
        exampleArr.forEach((item, i) => {
          code.push({ name: item.code, id: item.id });
        });
        this.nowSelectData = code;
      }
    },
    //依例全设
    copeTrData() {
      let exampleArr = JSON.parse(JSON.stringify(this.nowSelectRightData));
      if (exampleArr.length == 0) {
        this.$message.warning("请选择需操作的数据");
        return false;
      }
      if (exampleArr.length > 1) {
        this.$message.warning("只能选择一条数据");
        return false;
      }
      console.log(exampleArr);
      this.selectArr.forEach((item, i) => {
        item.sendType = exampleArr[0].sendType;
        // item.sendFenceType = exampleArr[0].sendFenceType;//下发类型
        item.alarmSource = exampleArr[0].alarmSource;
        item.startTime = exampleArr[0].startTime;
        item.endTime = exampleArr[0].endTime;
        item.alarmStartTime = exampleArr[0].alarmStartTime;
        item.alarmEndTime = exampleArr[0].alarmEndTime;
        item.alarmIn = exampleArr[0].alarmIn;
        item.alarmOut = exampleArr[0].alarmOut;
        item.alarmInDriver = exampleArr[0].alarmInDriver;
        item.alarmOutDriver = exampleArr[0].alarmOutDriver;
        item.speed = exampleArr[0].speed;
        item.overSpeedTime = exampleArr[0].overSpeedTime;
        item.travelLongTime = exampleArr[0].travelLongTime;
        item.travelSmallTime = exampleArr[0].travelSmallTime;
        item.openDoor = exampleArr[0].openDoor;
        item.communicationFlag = exampleArr[0].communicationFlag;
        item.gnssFlag = exampleArr[0].gnssFlag;
      });
      // console.log(this.selectArr);
    },

    freshArea() {
      $.fn.zTree.init($("#treeDemo"), this.setting, this.zNodes);
    },
    //全选
    selectAll(val) {
      var zTree = $.fn.zTree.getZTreeObj(val);
      var node = zTree.getNodes(); //得到全部节点
      var nodes = zTree.transformToArray(node);
      var checkNode = zTree.getCheckedNodes().length;
      if (checkNode < nodes.length) {
        zTree.checkAllNodes(true); //全选
        // console.log(zTree.getCheckedNodes(true))
        var code = [];
        nodes.forEach((item, i) => {
          if (item.deviceNumber || item.DeviceNumber) {
            console.log(item.Codes);
            code.push({ name: item.name });
          }
        });
        this.nowSelectData = code;
      } else {
        zTree.checkAllNodes(false); //取消
      }
    },
    zTreeOnCheck: function (event, treeId, treeNode) {
      var zTree = $.fn.zTree.getZTreeObj(treeId),
        checkCount = zTree.getCheckedNodes(true).length, //选中
        nocheckCount = zTree.getCheckedNodes(false).length, //未选中
        changeCount = zTree.getChangeCheckedNodes().length; //获取输入框勾选状态被改变的节点集合（与原始数据 checkedOld 对比）
      var code = [];
      for (var i = 0; i <= zTree.getCheckedNodes(true).length - 1; i++) {
        if (
          zTree.getCheckedNodes(true)[i].deviceNumber ||
          zTree.getCheckedNodes(true)[i].DeviceNumber
        ) {
          code.push({ name: zTree.getCheckedNodes(true)[i].name });
        }
      }
      // console.log(code,999)
      this.nowSelectData = code;
    },
    //异步获取子级
    zTreeOnExpand: function (event, treeId, treeNode) {
      // console.log(treeId)
      if (treeId == "treeDemo") {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        var parentZNode = zTree.getNodeByParam("id", treeNode.id, null); //获取指定父节点，code为本级节点， treeNode.code为当前点击节点的code值
        // console.log(treeId)
        // return
        if (!parentZNode.children) {
          let page = 0;
          let last_page = 1;
          this.$api
            .carUser({ cityId: parentZNode.id, pageNum: 500, page: 1 })
            .then((res) => {
              let page = 0;
              last_page = res.data.last_page;
              // parentZNode.icon = require("@/zTree/css/img/loading.gif");
              zTree.updateNode(treeNode);
              let intervalFunc = window.setInterval(() => {
                if (page < last_page) {
                  page = page + 1;
                  this.$api
                    .carUser({
                      cityId: parentZNode.id,
                      pageNum: 500,
                      page: page,
                    })
                    .then((res) => {
                      res.data.data.forEach((e) => {
                        // console.log(e)
                        let newNode = zTree.addNodes(parentZNode, e, false); //将获取到的子节点插入到父节点中
                      });
                    })
                    .catch((err) => {});
                } else {
                  parentZNode.icon = "";
                  zTree.updateNode(treeNode);
                  window.clearInterval(intervalFunc);
                }
              }, 300);
            })
            .catch((err) => {});
        }
      } else {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo1");
        var parentZNode = zTree.getNodeByParam("id", treeNode.id, null); //获取指定父节点，code为本级节点， treeNode.code为当前点击节点的code值
        // console.log(treeId)
        // return
        if (!parentZNode.children) {
          // parentZNode.icon = require("@/zTree/css/img/loading.gif");
          zTree.updateNode(treeNode);
          this.$api
            .CarConfigList({ dvcId: parentZNode.id })
            .then((res) => {
              res.data.data.forEach((e) => {
                // console.log(e)
                let newNode = zTree.addNodes(parentZNode, e, false); //将获取到的子节点插入到父节点中
              });
            })
            .catch((err) => {});
          parentZNode.icon = "";
          zTree.updateNode(treeNode);
        }
      }
    },
    //左侧分页
    handleCurrentChangeLeft: function (currentPage) {
      this.currentPageLeft = currentPage;
      this.moreSearch();
    },
    handleSizeChangeLeft: function (val) {
      this.pagesizeLeft = val;
      this.moreSearch();
    },

    //右侧分页
    handleSizeChange: function (val) {
      this.pagesize = val;
      this.getrecord();
      //   this.getBindData();
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage;
      this.getrecord();
      //   this.getBindData();
    },
    //数据分页
    getrecord() {
      let arr = [];
      for (
        let i = this.pagesize * (this.currentPage - 1);
        i < this.pagesize * this.currentPage;
        i++
      ) {
        if (this.selectArr[i]) {
          arr.push(this.selectArr[i]);
        }
      }
      this.$set(this, "loactiondata", arr);
    },

    checkAll(data) {
      // let allArr = []
      // let arr = []
      // arr['name'] = '1-2222222'
      // allArr.push(arr);
      // this.nowSelectData = allArr
      if (data.deviceNumber) {
        let checkNode = this.$refs.treedata.getCheckedNodes();
        let checkedId = checkNode.map((e) => {
          if (e.deviceNumber) {
            return e.name;
          }
        });
        let filArr = [
          ...checkedId,
          ...this.$refs.treedata.getHalfCheckedKeys(),
        ];
        let allArr = [];
        let code = filArr.filter((item, i) => {
          if (item) {
            let arr = [];
            arr["name"] = item;
            allArr.push(arr);
          }
        });
        this.nowSelectData = allArr;
      }
    },

    //选中table
    checkRightAll(val) {
      this.nowSelectRightData = val;
      console.log("=====表格项选中", this.nowSelectRightData);
    },
    // 选中
    handelSelect() {
      this.selectArr = this.selectArr ? this.selectArr : [];
      console.log("=====合并", this.selectArr, this.nowSelectData);
      this.selectArr = this.handleConcatArr(this.selectArr, this.nowSelectData);
      this.nowSelectData = [];
    },
    // 取消
    handleRemoveSelect() {
      this.handleRemoveTabList(this.nowSelectRightData, this.selectArr);
      this.nowSelectRightData = [];
    },
    handleConcatArr(selectArr, nowSelectData) {
      let arr = [];
      let carNos = [];
      if (selectArr.length > 0) {
        carNos = selectArr.map((e) => {
          return e.carNo;
        });
      }
      console.log(carNos);

      //   剔除重复车辆;
      let newArr = [];
      nowSelectData.forEach((e) => {
        if (carNos.indexOf(e.label) < 0) {
          newArr.push({ carNo: e.label, carId: e.id, configId: e.configId, deviceNumber: e.deviceNumber });
        }
      });
      arr = arr.concat(selectArr, newArr);
      this.total = arr.length;
      //   console.log(arr.length, '======');
      console.log(arr);
      return arr;
    },
    handleRemoveTabList(isNeedArr, tableArr) {
      if (isNeedArr.length && tableArr.length) {
        for (let i = 0; i < isNeedArr.length; i++) {
          for (let k = 0; k < tableArr.length; k++) {
            if (isNeedArr[i]["carNo"] === tableArr[k]["carNo"]) {
              tableArr.splice(k, 1);
              this.total = this.total - 1;
            }
          }
        }
      }
    },

    //更多搜索
    moreSearch(val) {
      // searchForm:{
      //   cardStatus:'',//卡类别
      //   emissionStage:'',//排放阶段
      //   endNumber:'', //尾号
      // },
      let params = {
        pageNo: this.currentPageLeft,
        pageSize: this.pagesizeLeft,
        cardStatus: this.searchForm.cardStatus,
        code: this.searchForm.emissionStage,
        endNumber: this.searchForm.endNumber.join(","),
      };

      api
        .moreBindCarSearch(params)
        .then((res) => {
          this.moreData = res.data;
          this.totalLeft = res.result.total;
        })
        .catch((err) => {});
    },

    // 前端导出
    exportToExcel() {
      let arr = JSON.parse(JSON.stringify(this.selectArr));
      arr.forEach((e) => {
        if (e.sendFenceType) {
          this.xfData.forEach((x) => {
            if (x["value"] == e.sendFenceType) {
              e.sendFenceType = x["label"];
            }
          });
        }
        if (e.alarmSource) {
          this.jkData.forEach((x) => {
            if (x["value"] == e.alarmSource) {
              e.alarmSource = x["label"];
            }
          });
        }
        e.alarmIn = e.alarmIn == 1 ? "是" : "否";
        e.alarmOut = e.alarmOut == 1 ? "是" : "否";
        e.alarmInDriver = e.alarmInDriver == 1 ? "是" : "否";
        e.alarmOutDriver = e.alarmOutDriver == 1 ? "是" : "否";
        e.openDoor = e.openDoor == 1 ? "是" : "否";
        e.communicationFlag = e.communicationFlag == 1 ? "是" : "否";
        e.gnssFlag = e.gnssFlag == 1 ? "是" : "否";
      });
      var option = {};
      option.fileName = "围栏内车统计";
      //  console.log(sheetFilter)
      option.datas = [
        {
          sheetData: arr,
          sheetName: "工地统计列表详情",
          // sheetFilter:sheetFilter,
          sheetFilter: [
            //列过滤
            "carNo",
            "sendFenceType",
            "alarmSource",
            "startTime",
            "endTime",
            "alarmIn",
            "alarmOut",
            "alarmInDriver",
            "alarmOutDriver",
            "speed",
            "overSpeedLastTime",
            "travelLongTime",
            "travelSmallTime",
            "openDoor",
            "communicationFlag",
            "gnssFlag",
          ],
          // sheetHeader:sheetHeader
          sheetHeader: [
            //第一行
            "监控对象",
            "下发类型",
            "报警来源",
            "开始时间",
            "结束时间",
            "驶入报警给平台",
            "驶出报警给平台",
            "驶入报警给驾驶员",
            "驶出报警给驾驶员",
            "最高速度（km/h）",
            "超速持续时间（s）",
            "行驶时间过长阈值（s）",
            "行驶时间不足阈值（s）",
            "允许开门",
            "进区域开启通信模块",
            "进区域不采集GNSS详细定位数据",
          ],
        },
      ];
      var toExcel = new ExportJsonExcel(option);
      toExcel.saveExcel();
    },
    // 后端导出
    backendExportToExcel() {
      let params = {
        carNo: this.inputRightCode,
        fenceId: this.fenceId,
      };
      this.download(
        "/location/fence_car/exportAll",
        {
          ...params,
        },
        `绑定_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.opSetting {
  text-align: center;
  height: calc(90vh - 350px) !important;
  margin-top: 230%;
}
.spacing {
  margin-top: 10px;
}

.demo .el-switch__label {
  position: absolute;
  display: none;
  color: #fff;
  font-size: 12px;
}
/*打开时文字位置设置*/
.demo .el-switch__label--right {
  z-index: 1;
  right: 21px;
}
/*关闭时文字位置设置*/
.demo .el-switch__label--left {
  z-index: 1;
  left: 19px;
}
/*显示文字*/
.demo .el-switch__label.is-active {
  display: block;
}
.left {
  position: relative;

  .searchCarinfoShow {
    position: absolute;
    top: 115px;
    width: 100%;
    height: 82%;
    background-color: #fff;
    z-index: 9999;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
    border: 1px solid #d2d2d2;
    border-radius: 4px;
    padding-top: 10px;
  }
}
.cell-input {
  width: 100%;
  height: 100%;
  border: 0;
  position: absolute;
  top: 0;
  left: 0;
  padding-left: 10px;
  padding-right: 10px;
  box-sizing: border-box;
}

.treedata {
  height: calc(90vh - 190px) !important;
  overflow-y: scroll;
}
</style>
